import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Order, PaymentStatus, OrderStatus } from './entities/order.entity';
import { CreateOrderDto } from './dto/create-order.dto';
import { UsersService } from '../users/users.service';
import { SubscriptionsService } from '../subscriptions/subscriptions.service';

/**
 * 订单服务
 */
@Injectable()
export class OrdersService {
  constructor(
    @InjectRepository(Order)
    private ordersRepository: Repository<Order>,
    private usersService: UsersService,
    private subscriptionsService: SubscriptionsService,
  ) {}

  /**
   * 创建订单
   */
  async create(userId: number, createOrderDto: CreateOrderDto): Promise<Order> {
    const { subscriptionType, duration } = createOrderDto;

    // 获取套餐信息
    const plan = await this.subscriptionsService.getPlan(subscriptionType, duration);
    if (!plan) {
      throw new NotFoundException('订阅套餐不存在');
    }

    // 生成订单号
    const orderNo = this.generateOrderNo();

    // 设置30分钟后过期
    const expiredAt = new Date(Date.now() + 30 * 60 * 1000);

    // 创建订单
    const order = this.ordersRepository.create({
      userId,
      orderNo,
      amount: plan.price,
      totalPrice: plan.price,
      subscriptionType,
      duration,
      planName: plan.name,
      paymentMethod: createOrderDto.paymentMethod,
      status: OrderStatus.PENDING,
      expiredAt,
    });

    return await this.ordersRepository.save(order);
  }

  /**
   * 查询用户订单列表
   */
  async findByUser(userId: number): Promise<Order[]> {
    return await this.ordersRepository.find({
      where: { userId },
      order: { createdAt: 'DESC' },
    });
  }

  /**
   * 查询单个订单
   */
  async findOne(id: number): Promise<Order> {
    const order = await this.ordersRepository.findOne({ where: { id } });
    if (!order) {
      throw new NotFoundException(`订单 #${id} 不存在`);
    }
    return order;
  }

  /**
   * 通过订单号查询
   */
  async findByOrderNo(orderNo: string): Promise<Order> {
    const order = await this.ordersRepository.findOne({ where: { orderNo } });
    if (!order) {
      throw new NotFoundException(`订单 ${orderNo} 不存在`);
    }
    return order;
  }

  /**
   * 更新订单支付状态
   */
  async updatePaymentStatus(
    orderNo: string,
    status: PaymentStatus,
    transactionId?: string,
  ): Promise<Order> {
    const order = await this.findByOrderNo(orderNo);
    
    order.paymentStatus = status;
    if (transactionId) {
      order.transactionId = transactionId;
    }
    if (status === PaymentStatus.PAID) {
      order.paidAt = new Date();
      
      // 更新用户订阅状态
      await this.usersService.updateSubscription(
        order.userId,
        order.subscriptionType as any,
        order.duration,
      );
    }

    return await this.ordersRepository.save(order);
  }

  /**
   * 处理支付成功回调
   */
  async handlePaymentSuccess(params: {
    orderNo: string;
    transactionId: string;
    paymentMethod: string;
    paidAt: Date;
    paidAmount: number;
  }): Promise<Order> {
    const { orderNo, transactionId, paymentMethod, paidAt, paidAmount } = params;

    console.log('\n========== 💰 处理支付成功回调 ==========');
    console.log('⏰ 时间:', new Date().toISOString());
    console.log('📦 参数:', JSON.stringify(params, null, 2));

    try {
      const order = await this.findByOrderNo(orderNo);

      console.log('📋 订单信息:', {
        订单号: order.orderNo,
        订单ID: order.id,
        用户ID: order.userId,
        当前状态: order.status,
        支付状态: order.paymentStatus,
        订单金额: order.totalPrice,
        套餐类型: order.subscriptionType,
        时长: order.duration,
      });

      // 防止重复处理
      if (order.status === OrderStatus.PAID || order.status === OrderStatus.COMPLETED) {
        console.log('⚠️ 订单已处理过，跳过');
        console.log('========== ✅ 处理完成（已处理过）==========\n');
        return order;
      }

      // 验证金额（允许0.01的误差）
      if (Math.abs(Number(order.totalPrice) - paidAmount) > 0.01) {
        console.error('❌ 订单金额不匹配:', {
          订单金额: order.totalPrice,
          实付金额: paidAmount,
          差额: Math.abs(Number(order.totalPrice) - paidAmount),
        });
        throw new Error('订单金额不匹配');
      }

      console.log('✅ 金额验证通过');

      // 更新订单状态
      console.log('🔄 更新订单状态为 PAID...');
      order.status = OrderStatus.PAID;
      order.paymentStatus = PaymentStatus.PAID;
      order.transactionId = transactionId;
      order.paidAt = paidAt;

      await this.ordersRepository.save(order);
      console.log('✅ 订单状态已更新');

      // 开通会员权益
      console.log('🔄 开始开通会员权益...');
      console.log('会员信息:', {
        用户ID: order.userId,
        套餐类型: order.subscriptionType,
        时长: order.duration,
      });

      try {
        await this.usersService.updateSubscription(
          order.userId,
          order.subscriptionType as any,
          order.duration,
        );

        console.log('✅ 会员权益开通成功');

        // 标记订单为已完成
        console.log('🔄 更新订单状态为 COMPLETED...');
        order.status = OrderStatus.COMPLETED;
        await this.ordersRepository.save(order);

        console.log('✅ 订单状态更新为 COMPLETED');
        console.log('========== 🎉 订单处理完成，会员已开通 ==========\n');
      } catch (error) {
        console.error('========== ❌ 开通会员失败 ==========');
        console.error('错误:', error);
        console.error('错误详情:', error.message);
        console.error('错误堆栈:', error.stack);
        
        // 订单保持PAID状态，需要手动处理
        console.log('⚠️ 更新订单状态为 PROCESSING（需要手动处理）');
        order.status = OrderStatus.PROCESSING;
        await this.ordersRepository.save(order);
        
        console.error('========== ❌ 处理失败 ==========\n');
        throw error;
      }

      return order;
    } catch (error) {
      console.error('========== ❌ 处理支付成功回调失败 ==========');
      console.error('错误:', error);
      console.error('错误详情:', error.message);
      console.error('错误堆栈:', error.stack);
      console.error('========== ❌ 处理结束 ==========\n');
      throw error;
    }
  }

  /**
   * 查询所有订单（管理员）
   */
  async findAll(params?: {
    page?: number;
    limit?: number;
    status?: OrderStatus;
    userId?: number;
  }): Promise<{ data: Order[]; total: number; page: number; limit: number }> {
    const { page = 1, limit = 20, status, userId } = params || {};

    const queryBuilder = this.ordersRepository
      .createQueryBuilder('order')
      .leftJoinAndSelect('order.user', 'user');

    if (status) {
      queryBuilder.andWhere('order.status = :status', { status });
    }

    if (userId) {
      queryBuilder.andWhere('order.userId = :userId', { userId });
    }

    queryBuilder.orderBy('order.createdAt', 'DESC');

    const skip = (page - 1) * limit;
    queryBuilder.skip(skip).take(limit);

    const [data, total] = await queryBuilder.getManyAndCount();

    return {
      data,
      total,
      page,
      limit,
    };
  }

  /**
   * 生成订单号（带项目前缀DTH）
   * 格式：DTH + 日期(8位) + 随机码(6位)
   * 示例：DTH202410301A2B3C
   * 
   * 用途：在多项目共用微信商户号时，通过前缀识别订单来源
   */
  private generateOrderNo(): string {
    const date = new Date();
    const dateStr = date.toISOString().slice(0, 10).replace(/-/g, '');
    const random = Math.random().toString(36).substring(2, 8).toUpperCase();
    return `DTH${dateStr}${random}`;
  }
}





